package com.thread.example.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.*;

/**
 * @Auther:
 * @Description:
 * @Date: 2019/11/1 16:24
 */
@Service
public class AsyncDemoService {

    @Async
    public Future<String> asyncService(List<String> list, int index, CountDownLatch countDownLatch) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            countDownLatch.countDown();
        }
        //System.out.println(Thread.currentThread().getName() + "---- finish ----- index = " + index);
        // 消息汇总
        return new AsyncResult<String>(Thread.currentThread().getName() + "---- index = " + index);
    }

    @Async
    public Future<String> asyncService1(List<String> list, int index) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //System.out.println(Thread.currentThread().getName() + "---- finish ----- index = " + index);
        // 消息汇总
        return new AsyncResult<String>(Thread.currentThread().getName() + "---- index = " + index);
    }

    public Queue<FutureTask<Integer>> zuse(List<Integer> list) {
//        List<FutureTask<Integer>> futures = new CopyOnWriteArrayList<>();
        Queue<FutureTask<Integer>> q = new LinkedList<FutureTask<Integer>>();
        ExecutorService executorService = Executors.newFixedThreadPool(4);


        for (Integer i : list) {
            FutureTask<Integer> future = new FutureTask<>(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    if (i == 10) {
                        Thread.sleep(10000000);
                    }
                    System.out.println("第 " + i + "条执行完毕!!!");
                    return i;
                }
            });
//            futures.add(future);
            q.add(future);
            executorService.submit(future);
        }
        executorService.shutdown();
//        return futures;
        return q;
        //return null;
    }



}
